<template>
    <TopNav />

    <div class="main_wrap" style="background-color: #f5f5f5;padding: 0;">
        <div class="top">
            <div class="row">
                <div class="form_item">
                    <span class="label">盘点日期：</span>
                    <el-date-picker v-model="strTime" ref="startTimeRef" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        :clearable="false" type="date" placeholder="请选择日期" size="large" style="width: 200px;" />
                </div>

                <div style="margin-right:10px;">至</div>
                <div class="form_item">

                    <el-date-picker v-model="endTime" ref="endTimeRef" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        :clearable="false" type="date" placeholder="请选择日期" size="large" style="width: 200px;" />
                </div>

                <el-radio-group v-model="dayType" size="large" @change="changeDateTypes">
                    <el-radio-button label="今天" value="0" />
                    <el-radio-button label="昨天" value="1" />
                    <el-radio-button label="近7天" value="2" />
                </el-radio-group>


                <el-button size="large" type="primary" @click="search" style="margin-left: 12px;">查询</el-button>

            </div>
            <el-button size="large" type="success" @click="newCheckOrder">新建盘点单</el-button>
        </div>
        <div class="table_wrap" ref="myTableRef">
            <!-- :header-cell-style="{ backgroundColor: 'var(--ev-c-black)', color: '#fff' }" -->
            <el-table :header-cell-style="{ backgroundColor: 'var(--el-color-primary)', color: '#fff' }" stripe
                :data="currentPageTableData"
                class-name="my_table">
                <el-table-column type="index" width="50" />
                <el-table-column prop="checkNumber" label="盘点单号" min-width="108" />

                <el-table-column prop="statusText" label="盘点状态" min-width="76">
                    <template #default="scope">
                       <span :class="scope.row.statusText==='盘点中'?'green':'red'"> {{scope.row.statusText}}</span>
                    </template>
                    </el-table-column>
                <el-table-column prop="checkTemplateName" label="盘点模板" min-width="76" />


                <el-table-column prop="createTime" label="创建时间" min-width="100" />

                <el-table-column label="操作" width="180" style="padding: 0;">
                    <template #default="scope">
                        <el-button type="danger" @click="beforeDelCheckOrder(scope.row)">
                            删除
                        </el-button>
                        <el-button type="primary" @click="openDesc(scope.row)">
                            详情
                        </el-button>

                    </template>
                </el-table-column>

            </el-table>
        </div>

        <div class="bottom_btns">

            <el-button size="large" type="primary" @click="prev" :disabled="currentPage == 1">上一页</el-button>

            <el-button size="large" type="primary" @click="next"
                :disabled="currentPage >= Math.ceil(total / pageSize)">下一页</el-button>

        </div>
    </div>

    <!--确认删除弹窗-->
    <el-dialog v-model="confirmDelVisible" class="order_desc_dialog" title="提示" width="800">
        <span>确认删除当前盘点单吗？</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" @click="confirmDelVisible = false">
                    取消
                </el-button>
                <el-button size="large" type="primary" @click="delOrder">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!--选择盘点模板弹窗-->
    <el-dialog v-model="checkTemplateDialogVisible" class="order_desc_dialog" title="请选择盘点模板" width="800">
        <div class="template_list">
            <div v-for="(item, index) in currentPageTemplateData" class="item"
                :class="{ active: index == currentTemplateIndex }" @click="currentTemplateIndex = index">
                <div class="text">
                    {{ item.name }}
                </div>
            </div>
        </div>
        <template #footer>
            <div class="template-dialog-footer">
                <div>
                    <el-button size="large" @click="prevTemplate" :disabled="currentTemplatePage == 1">
                        上一页
                    </el-button>
                    <el-button size="large" type="primary" @click="nextTemplate"
                        :disabled="currentTemplatePage >= Math.ceil(templateTotal / templatePageSize)">
                        下一页
                    </el-button>
                </div>
                <div>
                    <el-button size="large" @click="checkTemplateDialogVisible = false">
                        取消
                    </el-button>
                    <el-button size="large" type="primary"
                        @click="confirmSelectTemplate(currentPageTemplateData[currentTemplateIndex])">
                        确定
                    </el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
//@ts-nocheck
import { ElMessage } from 'element-plus'
import { getDateTimeString } from '@renderer/utils'
import { ref, onMounted, watch, onActivated, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@renderer/store/user'
import { getCheckList, delCheckOrder, getCheckTemplateList, createCheckOrder } from '@renderer/api/checkquery'
import { useRouter } from "vue-router";


const router = useRouter()

const currentType = ref(0)
const pageTableData = ref([]) //分页后的数据
const userStore = useUserStore()
const { userInfo, shopInfo, panelGoodsData, unPanelGoodsData } = storeToRefs(userStore)
const shopID = shopInfo.value.shopID
const saleOrganizationID = userInfo.value.user_organizationId



const tableData = ref([])

const pageSize = ref(1)
const myTableRef = ref()
const currentPage = ref(1)
const total = ref(0)
const confirmDelVisible = ref(false) //确认删除弹窗
const checkTemplateDialogVisible = ref(false) //盘点模板弹窗
//模板分页相关
const templateList = ref([])
const templatePageSize = ref(6)
const currentTemplatePage = ref(1)
const templateTotal = ref(0)
const currentTemplateIndex = ref(0)
const pageTemplateData = ref([]) //分页后的模板数据

//模板当前页数据
const currentPageTemplateData = computed(() => {

    return pageTemplateData.value[currentTemplatePage.value - 1]
})
onActivated(() => {
    console.log('onActivated!~')
    search()
})

onMounted(() => {
    console.log('onMounted~~')


    let tableHeight = myTableRef.value.offsetHeight
    let singleRowHeight = 49 //每行高度
    pageSize.value = Math.floor(tableHeight / singleRowHeight) - 1 //每页最多显示行数(-1 是减去header)
    console.log(pageSize.value)

})
function prev() {
    if (currentPage.value <= 1) return
    currentPage.value--
}
function next() {
    if (currentPage.value >= pageTableData.value.length) return
    currentPage.value++
}

function prevTemplate() {
    if (currentTemplatePage.value <= 1) return
    currentTemplatePage.value--
}
function nextTemplate() {
    if (currentTemplatePage.value >= pageTemplateData.value.length) return
    currentTemplatePage.value++
}



//当前页数据
const currentPageTableData = computed(() => {
    console.log(pageTableData.value, [currentPage.value - 1])

    console.log(pageTableData.value[currentPage.value - 1])
    return pageTableData.value[currentPage.value - 1]
})
const today = getDateTimeString(new Date().getTime())
const dayType = ref('0')
const strTime = ref(today)
const endTime = ref(today)

//日期改变后设置按钮组选中状态
watch([strTime, endTime], () => {
    setBtnsTypeByDate()
})

//今天、昨天、近7天切换
function changeDateTypes(val) {
    if (val === '0') {
        setToday()
    } else if (val === '1') {
        setYesterday()
    } else if (val === '2') {
        setLastWeek()
    }
}
function setToday() { //将日期设为今天
    const dateString = getDateTimeString(new Date().getTime())
    strTime.value = dateString
    endTime.value = dateString

}

function setYesterday() { //将日期设为昨天昨天
    const dateString = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    strTime.value = dateString
    endTime.value = dateString

}
function setLastWeek() { //将日期设为近7天

    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
    const startDateString = getDateTimeString(new Date(start).getTime())
    strTime.value = startDateString
    endTime.value = getDateTimeString(new Date().getTime())
}

//根据日期设置按钮组选中状态
function setBtnsTypeByDate() {
    const todayStr = getDateTimeString(new Date().getTime())
    const yesterdayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    const lastWeekDayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24 * 6)
    if (strTime.value === todayStr && endTime.value === todayStr) {
        dayType.value = '0'
    } else if (strTime.value === yesterdayStr && endTime.value === yesterdayStr) {
        dayType.value = '1'
    } else if (strTime.value === lastWeekDayStr && endTime.value === todayStr) {
        dayType.value = '2'
    } else {
        dayType.value = ''
    }
}







async function search() {
    console.log('search')
    if (strTime.value && endTime.value && new Date(endTime.value).getTime() < new Date(strTime.value).getTime()) {
        endTime.value = ''
        ElMessage({
            message: '结束时间不能小于开始时间',
            type: 'warning',
        })
        return
    }
    currentPage.value = 1

    try {
        const { data } = await getCheckList(saleOrganizationID, shopID, strTime.value, endTime.value)
    tableData.value = data
    pageTableData.value = paginateData(data, pageSize.value)
    } catch (error) {
        console.log(error)
    }
   



}
//分页
function paginateData(data, pageSize) {
    console.log(data)
    const pages = [];
    for (let i = 0; i < data.length; i += pageSize) {
        pages.push(data.slice(i, i + pageSize));
    }
    console.log(pages)
    return pages;
}
//详情
function openDesc(row) {

    router.push({ name: 'newcheck', query: { row: JSON.stringify(row) } })
}

const currentRow = ref({})
//删除盘点单
function beforeDelCheckOrder(row) {
    currentRow.value = row
    confirmDelVisible.value = true
}
async function delOrder() {
    const shopCheckID = currentRow.value.id
    try {
        const {msg} = await delCheckOrder(saleOrganizationID,shopCheckID)
    ElMessage({
        message:msg,
        type: 'success',
    })
    const index = pageTableData.value[currentPage.value - 1].findIndex(item => item.id == shopCheckID)
    pageTableData.value[currentPage.value - 1].splice(index, 1)
    confirmDelVisible.value = false
    } catch (error) {
        console.log(error)
    }
    
}



//新建盘点单
async function newCheckOrder() {
    try {
        const { data } = await getCheckTemplateList(saleOrganizationID, shopID)
    data.unshift({
        name: "全部商品",
        id: 0
    })
    //添加全部
    templateList.value = data
    templateTotal.value = data.length
    pageTemplateData.value = paginateData(data, templatePageSize.value)
    currentTemplateIndex.value = 0
    currentTemplatePage.value = 1


    checkTemplateDialogVisible.value = true
    } catch (error) {
        console.log(error)
    }
   
    // router.push({ name: 'newtransfer' })
}

//选择盘点模板
async function confirmSelectTemplate(item) {
    try {
        const { msg } = await createCheckOrder(saleOrganizationID, shopID, item.id)
    await search()
    ElMessage({
        message: msg,
        type: 'success',
    })
    checkTemplateDialogVisible.value = false
    } catch (error) {
        console.log(error)
    }
    
}
</script>
<style lang='scss' scoped>
.custom_select {

    .el-select-dropdown__item {

        line-height: 50px;
        height: 50px;

    }
}
</style>
<style lang='scss' scoped>
.custom_search_class {
    :deep(.search-keyboard-dialog) {
        left: 10px;
        top: 160px;
        bottom: unset;
        width: 100%;
    }
}

.top {
    padding: 10px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .row {
        display: flex;
        align-items: center;


        .form_item {
            display: flex;
            align-items: center;
            margin-right: 10px;

            .label {
                width: 80px;

            }
        }

    }
}

.table_wrap {
    padding: 0 10px;
    height: calc(100% - 120px - 50px);
    .green{
        color: var(--el-color-success);
    }
    .red{
        color: var(--el-color-danger);
    }
}

.bottom_btns {
    position: absolute;
    bottom: 5px;
    left: 10px;
}

.shop_list {
    padding: 10px 0;
}

//调拨单状态颜色  0\1\2\3\4 (创建、待接收、接收、退回、撤回)
.status_0 {
    color: var(--el-color-success);
}

.status_1 {
    color: var(--el-color-warning);
}

.status_2 {
    color: var(--el-color-primary);
}

.status_3 {
    color: var(--el-color-danger);
}

.status_4 {
    color: var(--el-color-info);
}


.template_list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 10px;

    .item {
        border: 1px solid var(--el-border-color);
        border-radius: var(--el-border-radius-base);
        padding: 10px;
        box-sizing: border-box;

        .text {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }


        &.active {
            background-color: var(--el-color-primary);
            color: #fff;
        }
    }
}

.template-dialog-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>